/**
 * 通用列表查询
 * @url admin/system/base/getList
 * @description 通用列表查询，支持分页和搜索
 */
module.exports = {
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: '' };
		
		// 表名映射配置
		const dbNameMap = {
			user: 'uni-id-users',
			role: 'uni-id-roles',
			permission: 'uni-id-permissions',
			menu: 'opendb-admin-menus'
		};
		
		// 字段映射配置（用于搜索）
		const searchFieldsMap = {
			user: ['username', 'nickname', 'mobile', 'email'],
			role: ['role_id', 'role_name'],
			permission: ['permission_id', 'permission_name'],
			menu: ['name', 'url']
		};
		
		// 默认排序字段
		const defaultOrderByMap = {
			user: 'last_login_date',
			role: 'create_date',
			permission: 'create_date',
			menu: 'sort'
		};
		
		// 业务逻辑开始-----------------------------------------------------------
		let {
			type, // user/role/permission/menu
			pageIndex = 1,
			pageSize = 20,
			keyword = '',
			orderBy,
			orderType = 'desc',
			where = {} // 额外的查询条件
		} = data;
		
		if (!type || !dbNameMap[type]) {
			return { code: -1, msg: '类型参数错误' };
		}
		
		let dbName = dbNameMap[type];
		let searchFields = searchFieldsMap[type] || [];
		let defaultOrderBy = defaultOrderByMap[type] || 'create_date';
		
		// 构建查询条件
		let queryWhere = { ...where };
		if (keyword && searchFields.length > 0) {
			let keywordConditions = searchFields.map(field => ({
				[field]: new RegExp(keyword, 'i')
			}));
			queryWhere = _.and([
				queryWhere,
				_.or(keywordConditions)
			]);
		}
		
		// 构建查询
		let query = db.collection(dbName).where(queryWhere);
		
		// 字段筛选（根据类型）
		if (type === 'user') {
			query = query.field('username,nickname,mobile,email,role,status,last_login_date,avatar,create_date,dcloud_appid');
		} else if (type === 'role') {
			query = query.field('role_id,role_name,permission,comment,create_date');
		} else if (type === 'permission') {
			query = query.field('permission_id,permission_name,comment,create_date');
		} else if (type === 'menu') {
			query = query.field('menu_id,name,icon,url,parent_id,sort,enable,create_date');
		}
		
		// 排序
		let sortField = orderBy || defaultOrderBy;
		query = query.orderBy(sortField, orderType);
		
		// 分页
		query = query.skip((pageIndex - 1) * pageSize).limit(pageSize);
		
		// 查询列表
		let listRes = await query.get();
		
		// 获取总数
		let countRes = await db.collection(dbName).where(queryWhere).count();
		
		// 处理数据（根据类型进行特殊处理）
		let list = listRes.data;
		if (type === 'role') {
			// 处理角色权限信息
			let permissionRes = await db.collection('uni-id-permissions').get();
			let permissionMap = {};
			permissionRes.data.forEach(perm => {
				permissionMap[perm.permission_id] = perm.permission_name;
			});
			
			list.forEach(role => {
				if (Array.isArray(role.permission)) {
					role.permission_list = role.permission.map(p => {
						if (typeof p === 'string') {
							return permissionMap[p] || p;
						}
						return permissionMap[p.permission_id] || p.permission_name || p;
					});
					role.permission_display = role.permission_list.join('、');
				} else {
					role.permission_list = [];
					role.permission_display = '';
				}
			});
		} else if (type === 'user') {
			// 处理用户角色信息
			let roleRes = await db.collection('uni-id-roles').get();
			let roleMap = {};
			roleRes.data.forEach(role => {
				roleMap[role.role_id] = role.role_name;
			});
			
			list.forEach(user => {
				if (Array.isArray(user.role)) {
					user.role_list = user.role.map(r => {
						if (typeof r === 'string') {
							return roleMap[r] || r;
						}
						return roleMap[r.role_id] || r.role_name || r;
					});
					user.role_display = user.role_list.join('、');
				} else {
					user.role_list = [];
					user.role_display = '';
				}
				
				// 处理应用ID
				if (Array.isArray(user.dcloud_appid)) {
					user.dcloud_appid_display = user.dcloud_appid.join('、');
				} else {
					user.dcloud_appid_display = user.dcloud_appid || '';
				}
			});
		}
		
		res.data = {
			list,
			total: countRes.total,
			pageIndex,
			pageSize
		};
		
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}

